package com.ihunanren.weixin.module.screen.school;

import static com.google.common.base.Strings.isNullOrEmpty;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.citrus.turbine.Context;
import com.alibaba.citrus.turbine.Navigator;
import com.alibaba.citrus.turbine.dataresolver.Param;
import com.google.common.collect.Maps;
import com.ihunanren.biz.weixin.ao.ISchoolCurriculumAO;
import com.ihunanren.common.CalendarUtil;
import com.ihunanren.common.CollectionUtils;
import com.ihunanren.common.auth.DES;
import com.ihunanren.dao.pojo.SchoolCurriculumDefinedDO;

public class Password {
	@Autowired
	private ISchoolCurriculumAO schoolCurriculumAO;
	
	private final static Logger log = LoggerFactory.getLogger(Password.class);

	public void execute(@Param(name = "sign") String sign, Navigator nav,
			Context context) {
		
		try {
			String str = DES.decrypt(sign,DES.DEFAULT_KEY);
			Map<String, String> map = split(str);
			if(CollectionUtils.isEmpty(map) || isNullOrEmpty(map.get("email"))){
				context.put("errorMsg", "非法请求");
				return;
			}
			SchoolCurriculumDefinedDO definedDO = schoolCurriculumAO.getByEmail(map.get("email"));
			if(definedDO == null){
				context.put("errorMsg", "非法请求");
				return;
			}
			if(definedDO.getStatus().intValue() == 1){
				context.put("errorMsg", "该用户已激活");
				return;
			}
			String sendTime = map.get("sendtime");
			if (CalendarUtil.getTimeIntervalMins(definedDO.getGmtCreate(),
					CalendarUtil.toDate(sendTime, CalendarUtil.TIME_PATTERN)) > 30) {
				context.put("errorMsg", "链接已经失效");
				return;
			}
			context.put("email", map.get("email"));
			context.put("sign", sign);
		} catch (Exception e) {
			log.error("Password catch a exception.",e);
		}
	}
	
	private Map<String, String> split(String str) {
		if (isNullOrEmpty(str))
			return null;

		String[] arrays = str.split(";");

		if (arrays == null || arrays.length != 4) {
			return null;
		}

		Map<String, String> map = Maps.newHashMap();
		map.put("name", arrays[0]);
		map.put("email", arrays[1]);
		map.put("diyName", arrays[2]);
		map.put("sendTime", arrays[3]);
		return map;
	}
	
	
}
